package com.sword.demo.quartz.config;

import com.sword.demo.quartz.properties.SchedulerProperties;
import com.sword.demo.quartz.service.ClockService;
import com.sword.demo.quartz.util.QuartzUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

/**
 * 定时任务-配置类
 * @author sword
 * @date 2022/11/17 17:07
 */
@Configuration
@Slf4j
@RequiredArgsConstructor
public class SchedulerConfig {

    /**
     * 定时任务-参数
     */
    private final SchedulerProperties schedulerProperties;

    /**
     * 时钟-定时任务详情
     * @param clockService 时钟服务
     * @return 时钟-定时任务详情
     * @author wukongjian
     * @date 2019/10/16 10:10
     */
    @Bean
    public MethodInvokingJobDetailFactoryBean clockJobDetail(ClockService clockService) {
        return QuartzUtil.createJobDetail(clockService, "clock");
    }

    /**
     * 时钟-定时任务触发器
     * @param clockJobDetail 时钟-定时任务详情
     * @return org.springframework.scheduling.quartz.CronTriggerFactoryBean 时钟-定时任务触发器
     * @author wukongjian
     * @date 2019/10/16 10:10
     */
    @Bean
    public CronTriggerFactoryBean clockCronTrigger(JobDetail clockJobDetail) {
        return QuartzUtil.createCronTrigger(clockJobDetail, "* * * * * ?");
    }



    /**
     * Quartz定时任务总控制器
     * @param cronTriggers 配置的所有定时任务触发器
     * @return Quartz定时任务总控制器
     * @author wukongjian
     * @date 2019/10/16 9:35
     */
    @Bean
    public SchedulerFactoryBean scheduler(Trigger[] cronTriggers) {
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        // 设置定时任务触发器
        schedulerFactoryBean.setTriggers(cronTriggers);
        // 设置自动启动定时任务
        schedulerFactoryBean.setAutoStartup(schedulerProperties.isEnabled());
        log.info("定时任务{}启动", schedulerProperties.isEnabled() ? "已" : "未");
        return schedulerFactoryBean;
    }
}
